import { setSetting, type ApplianceDetailOption, type ApplianceSetting } from '@/api/appliance'
import {
  BSH_COMMON_ENUMTYPE_FAVORITE_FUNCTIONALITY_PROGRAM,
  BSH_COMMON_OPRION_BASEPROGRAM,
  DISHWASHER_PROGRAM_SELFDEFINE1,
} from '@/constants/Command'
import type { ApplianceProgram } from '@/types/appliance'

import { trackEvent, TrackType } from '@/dataReport/tracks'
import { safeTrack } from '@/dataReport/dataReportUtil'

const SettingPrefix = 'BSH.Common.Setting.Favorite'
const ProgramPrefix = 'BSH.Common.Program.Favorite'
const SettingOn = 'BSH.Common.EnumType.Favorite.Functionality.Program'
const SettingOff = 'BSH.Common.EnumType.Favorite.Functionality.Off'
const EnableDelay = 500

/**
 * 获取settings接口中的favorite
 * @param settings
 * @returns
 */
export function getSettingsFavorite(settings: ApplianceSetting[]) {
  type FavoriteSettingType = {
    favoriteIndex?: string
    funcKey?: string
    key?: string
    collect?: boolean
    funcValue?: string
    name?: string
    baseProgramKey?: string
  }
  let newList = settings.reduce((tempSettings: FavoriteSettingType[], setting) => {
    if (setting.key.startsWith('BSH.Common.Setting.Favorite')) {
      const sortKey = setting.key.replace(/^BSH\.Common\.Setting\.Favorite\.(\d+)\.(\S+)$/, '$1')
      tempSettings[parseInt(sortKey) - 1] = tempSettings[parseInt(sortKey) - 1]
        ? tempSettings[parseInt(sortKey) - 1]
        : {}
      tempSettings[parseInt(sortKey) - 1].favoriteIndex = sortKey
      tempSettings[parseInt(sortKey) - 1].funcKey = `BSH.Common.Setting.Favorite.${sortKey}.Functionality`
      tempSettings[parseInt(sortKey) - 1].key = `BSH.Common.Program.Favorite.${sortKey}`
      if (setting.value instanceof Array && setting.value.length > 0) {
        tempSettings[parseInt(sortKey) - 1].baseProgramKey = setting.value[0].key
      }

      if (setting.key.endsWith(`${sortKey}.Functionality`)) {
        tempSettings[parseInt(sortKey) - 1].collect =
          setting.value === BSH_COMMON_ENUMTYPE_FAVORITE_FUNCTIONALITY_PROGRAM ? true : false
        tempSettings[parseInt(sortKey) - 1].funcValue = setting.value as string
      } else if (setting.key.endsWith(`${sortKey}.Name`)) {
        tempSettings[parseInt(sortKey) - 1].name = setting.value as string
      }
    }

    return tempSettings
  }, [])
  return newList
}

/**
 * 获取所有程序过滤收藏程序后的程序列表
 * @param programs
 * @returns
 */
export function filterFavoritePrograms(programs: ApplianceProgram.Scope[]) {
  return programs.filter((program) => {
    return (
      !program.key.match(/^BSH\.Common\.Program\.Favorite\.(\d+)$/) &&
      program.key != DISHWASHER_PROGRAM_SELFDEFINE1 &&
      program.key != BSH_COMMON_OPRION_BASEPROGRAM
    )
  })
}

/**
 * 加载收藏程序的keyIndex
 * @param keySource
 * @param activeProgramKey
 * @param settings
 * @param keyGetterIndex
 * @returns
 */
/**
 *  type KeySource = 'current' | 'latest' | 'getter'
 *     - current: 当前的收藏程序Key
 *     - latest: 最新可用的收藏程序Key
 *     - getter: 只取自Getter函数
 */
export function loadKeyIndex(
  keySource: string,
  activeProgramKey: string,
  settings: ApplianceSetting[],
  keyGetterIndex?: string
) {
  if (!keySource) throw new Error('Key source does not exist')

  let keyIndex = null
  if (keySource === 'current') {
    const regex = new RegExp(`^${ProgramPrefix}.(\\d+)$`)
    const result = activeProgramKey.match(regex)
    if (result) {
      keyIndex = result[1]
    }
  } else if (keySource === 'latest') {
    for (const setting of settings) {
      const match = setting.key?.match(/^BSH\.Common\.Setting\.Favorite\.(\d+)\.Functionality$/)
      // 是 Functionality 且 收藏点位不在启用中
      if (match && setting.value === SettingOff) {
        keyIndex = match[1]
        break
      }
    }
  } else if (keySource === 'getter') {
    keyIndex = keyGetterIndex
  }
  if (!keyIndex) {
    keyIndex = '001'
  }
  if (!keyIndex) {
    throw new Error('Current program cannot match a valid key')
  }
  return keyIndex
}

// 关闭收藏
export function setFavoriteOff(haId: string, keyIndex: string) {
  const key = `${SettingPrefix}.${keyIndex}.Functionality`
  const value = SettingOff
  return sendSettings(haId, key, value, keyIndex)
}

// 开启收藏
export function setFavoriteOn(haId: string, keyIndex: string) {
  const key = `${SettingPrefix}.${keyIndex}.Functionality`
  const value = SettingOn
  return sendSettings(haId, key, value, keyIndex)
}

// 设置收藏名称
export function setFavoriteName(haId: string, keyIndex: string, programName: string) {
  const key = `${SettingPrefix}.${keyIndex}.Name`
  const value = programName
  return sendSettings(haId, key, value, keyIndex)
}

// 设置收藏的默认配置项
export function setFavoriteOptions(haId: string, keyIndex: string, programOptions: FavoriteOptionsType[]) {
  const key = `${SettingPrefix}.${keyIndex}.Program`
  const value = programOptions
  return sendSettings(haId, key, value, keyIndex)
}

// 发送设置命令
export async function sendSettings(haId: string, key: string, value: string | FavoriteOptionsType[], keyIndex: string) {
  if (!keyIndex) throw new Error('KeyIndex does not exist')
  try {
    return await setSetting(haId, key, value)
  } catch (error) {}
}

export type FavoriteOptionsType = {
  key: string
  name?: string
  options?: ApplianceDetailOption[]
}
/**
 * 将当前程序设置为收藏程序
 * @param {string} programName 收藏程序的名称
 */
export async function setFavorite(
  haId: string,
  keyIndex: string,
  programName?: string,
  programOptions?: FavoriteOptionsType[]
) {
  let res: any = await Promise.all([
    // 设置收藏程序配置项
    setFavoriteOptions(haId, keyIndex, programOptions as FavoriteOptionsType[]),
    // 设置收藏程序名称
    setFavoriteName(haId, keyIndex, programName || ''),
  ])
  await new Promise<void>((r) => setTimeout(() => r(), EnableDelay))
  await setFavoriteOn(haId, keyIndex)
  return res[0]
}
